﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HUIBackgroundMatch : MonoBehaviour {

    public bool bForUpdateTest = false;

    private Canvas _canvas;
    public Canvas canvas
    {
        get
        {
            if (_canvas == null)
            {
                Canvas[] canvasArray = GameObject.FindObjectsOfType<Canvas>();
                foreach (Canvas canvas in canvasArray)
                {
                    if (canvas.isRootCanvas)
                    {
                        _canvas = canvas;
                        //Debug.LogError("---------: " + canvas.name);
                        break;
                    }
                }
            }
            return _canvas;
        }
    }

	// Use this for initialization
	void Start  () {

        if (!canvas.isActiveAndEnabled)
        {
            bForUpdateTest = true;
        }
        // 有些时候会出现未初始化的情况
        if (canvas.GetComponent<RectTransform>().sizeDelta == new Vector2(100f, 100f))
        {
            bForUpdateTest = true;
        }

        RectTransform rect = GetComponent<RectTransform>();
        if (rect)
        {
            //Debug.LogError("name:" + canvas.name + " state: " + canvas.isActiveAndEnabled + "  sizeDelta:" + canvas.GetComponent<RectTransform>().sizeDelta.ToString());
            float scaleFactor = canvas.GetComponent<RectTransform>().sizeDelta.y / rect.sizeDelta.y;
            rect.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
        }
    }
	
	// Update is called once per frame
	void Update () {
        if (bForUpdateTest)
        {
            RectTransform rect = GetComponent<RectTransform>();
            if (rect)
            {
                float scaleFactor = canvas.GetComponent<RectTransform>().sizeDelta.y / rect.sizeDelta.y;
                rect.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
                bForUpdateTest = !canvas.isActiveAndEnabled;

                if (canvas.GetComponent<RectTransform>().sizeDelta == new Vector2(100f, 100f))
                {
                    bForUpdateTest = true;
                }
            }
        }
    }
}
